function showCompanyIntro() {
    console.log("Suanfamama is the leading company in AI.");
    
    // Update status
    document.getElementById('status').textContent = 'Showing company info in console...';
}

class GameClient {
    constructor(isTestMode = false) {
        this.isTestMode = isTestMode;
        // Canvas setup
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.canvas.width = 800;
        this.canvas.height = 800;
        
        // Game state
        this.gameState = 'ready'; // ready, running, paused, ended
        this.mazeSize = 'small';
        this.mazeSizes = {
            'small': { size: 10, cellSize: 60 },
            'medium': { size: 20, cellSize: 30 },
            'large': { size: 30, cellSize: 20 },
            'ultra': { size: 40, cellSize: 15 }
        };
        
        // Snake state
        this.snake = {
            position: { x: 1, y: 1 },
            direction: 'right',
            length: 3,
            trail: []
        };
        
        // Game settings
        this.score = 0;
        this.energy = 100;
        this.currentMaze = null;
        this.food = null;
        
        // AI settings
        this.perceptionRange = 3;  // How far snake can "see"
        this.isAIEnabled = false;  // Toggle between manual/AI control
        this.explorationRate = 0.1; // Chance to explore random moves
        
        // Speed settings
        this.baseSpeed = 300;
        this.currentSpeed = 300;
        this.speedMultiplier = 0.95; // Speed increases by 5% per food
        this.gameLoop = null;
        
        // Energy system
        this.maxEnergy = 100;
        this.energy = this.maxEnergy;
        this.moveEnergyCost = 0.5;    // Energy cost per move
        this.foodEnergyGain = 25;     // Energy gained from food
        
        // Food types
        this.foodTypes = {
            apple: {
                color: '#4CAF50',      // Green apple
                energyGain: 25,        // Positive energy gain
                scoreGain: 10,         // Positive score
                probability: 0.7       // 70% chance of apple
            },
            poison: {
                color: '#F44336',      // Red poison
                energyLoss: -15,       // Negative energy impact
                scoreLoss: -5,         // Negative score
                probability: 0.3       // 30% chance of poison
            }
        };
        
        // Multiple food management
        this.foods = {
            apples: [],    // Array to hold multiple apples
            poisons: []    // Array to hold multiple poisons
        };
        this.maxApples = 3;   // Maximum number of apples at once
        this.maxPoisons = 2;  // Maximum number of poisons at once
        
        // Initialize
        this.setupControls();
        this.generateMaze(this.mazeSizes.small.size);
        this.setupPanelToggle();
    }
    
    generateMaze(size) {
        const mazeConfig = this.mazeSizes[this.mazeSize];
        this.currentMaze = Array(mazeConfig.size).fill().map(() => Array(mazeConfig.size).fill(1));
        const stack = [];
        const start = { x: 1, y: 1 };
        
        // Adjust generation parameters for ultra size
        const isUltra = size === 40;
        const complexity = isUltra ? 0.6 : 0.4;  // More complex for ultra
        
        // Add more random paths for ultra size
        if (isUltra) {
            for (let i = 0; i < size; i += 4) {
                for (let j = 0; j < size; j += 4) {
                    if (Math.random() < complexity) {
                        this.currentMaze[i][j] = 0;
                    }
                }
            }
        }
        
        // Recursive backtracking algorithm
        const visit = (x, y) => {
            this.currentMaze[x][y] = 0;
            
            const directions = [
                { dx: 0, dy: 2 },  // right
                { dx: 2, dy: 0 },  // down
                { dx: 0, dy: -2 }, // left
                { dx: -2, dy: 0 }  // up
            ].sort(() => Math.random() - 0.5);
            
            for (const dir of directions) {
                const nextX = x + dir.dx;
                const nextY = y + dir.dy;
                
                if (nextX > 0 && nextX < size - 1 && nextY > 0 && nextY < size - 1 
                    && this.currentMaze[nextX][nextY] === 1) {
                    this.currentMaze[x + dir.dx/2][y + dir.dy/2] = 0;
                    stack.push({ x: nextX, y: nextY });
                }
            }
        };
        
        visit(start.x, start.y);
        while (stack.length > 0) {
            const current = stack.pop();
            visit(current.x, current.y);
        }
        
        this.placeFoods();
        this.render();
        
        // Update maze size display
        document.getElementById('maze-size').textContent = 
            this.mazeSize.charAt(0).toUpperCase() + this.mazeSize.slice(1);
    }
    
    render() {
        if (this.gameState !== 'running' && this.gameState !== 'paused') return;
        
        // Clear canvas
        this.ctx.fillStyle = '#000';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        
        const cellSize = this.mazeSizes[this.mazeSize].cellSize;
        
        // Adjust rendering for ultra size
        if (this.mazeSize === 'ultra') {
            this.ctx.font = '10px Arial';  // Smaller font for ultra
        } else {
            this.ctx.font = '12px Arial';
        }
        
        // Draw maze
        this.currentMaze.forEach((row, i) => {
            row.forEach((cell, j) => {
                if (cell === 1) {
                    this.ctx.fillStyle = '#666';
                    this.ctx.fillRect(
                        i * cellSize, 
                        j * cellSize, 
                        cellSize, 
                        cellSize
                    );
                }
            });
        });
        
        // Draw snake
        this.ctx.fillStyle = '#4CAF50';
        this.snake.trail.forEach(pos => {
            this.ctx.fillRect(
                pos.x * cellSize + 2,
                pos.y * cellSize + 2,
                cellSize - 4,
                cellSize - 4
            );
        });
        
        // Draw all foods
        this.foods.apples.forEach(apple => {
            this.drawFood(apple, '#4CAF50', true);  // Green circle for apple
        });
        
        this.foods.poisons.forEach(poison => {
            this.drawFood(poison, '#F44336', false);  // Red diamond for poison
        });
        
        requestAnimationFrame(() => this.render());
    }
    
    placeFoods() {
        // Place apples if needed
        while (this.foods.apples.length < this.maxApples) {
            const apple = this.generateFoodPosition('apple');
            if (apple) this.foods.apples.push(apple);
        }
        
        // Place poisons if needed
        while (this.foods.poisons.length < this.maxPoisons) {
            const poison = this.generateFoodPosition('poison');
            if (poison) this.foods.poisons.push(poison);
        }
    }

    generateFoodPosition(type) {
        let attempts = 0;
        const maxAttempts = 50;
        
        while (attempts < maxAttempts) {
            const x = Math.floor(Math.random() * this.currentMaze.length);
            const y = Math.floor(Math.random() * this.currentMaze.length);
            
            // Check if position is valid (not wall, not snake, not other food)
            if (this.isValidFoodPosition(x, y)) {
                return { x, y, type };
            }
            attempts++;
        }
        return null;
    }

    isValidFoodPosition(x, y) {
        // Check for walls
        if (this.currentMaze[x][y] === 1) return false;
        
        // Check for snake
        if (this.snake.trail.some(pos => pos.x === x && pos.y === y)) return false;
        
        // Check for other foods
        const allFoods = [...this.foods.apples, ...this.foods.poisons];
        if (allFoods.some(food => food.x === x && food.y === y)) return false;
        
        return true;
    }

    drawFood(food, color, isApple) {
        const cellSize = this.mazeSizes[this.mazeSize].cellSize;
        this.ctx.fillStyle = color;
        
        if (isApple) {
            // Draw circular apple
            const centerX = food.x * cellSize + cellSize/2;
            const centerY = food.y * cellSize + cellSize/2;
            const radius = (cellSize - 8) / 2;
            
            this.ctx.beginPath();
            this.ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
            this.ctx.fill();
        } else {
            // Draw diamond-shaped poison
            const x = food.x * cellSize;
            const y = food.y * cellSize;
            
            this.ctx.beginPath();
            this.ctx.moveTo(x + cellSize/2, y + 4);
            this.ctx.lineTo(x + cellSize - 4, y + cellSize/2);
            this.ctx.lineTo(x + cellSize/2, y + cellSize - 4);
            this.ctx.lineTo(x + 4, y + cellSize/2);
            this.ctx.closePath();
            this.ctx.fill();
        }
    }
    
    updateUI() {
        document.getElementById('score').textContent = this.score;
        document.getElementById('energy').textContent = Math.round(this.energy);
        document.getElementById('status').textContent = 
            this.gameState.charAt(0).toUpperCase() + this.gameState.slice(1);
        
        // Change energy color based on level
        const energyElement = document.getElementById('energy');
        if (this.energy < 20) {
            energyElement.style.color = '#ff0000';  // Red for low energy
        } else if (this.energy < 50) {
            energyElement.style.color = '#ffa500';  // Orange for medium energy
        } else {
            energyElement.style.color = '#ffffff';  // White for good energy
        }
        
        // Add food type indicator
        const statusText = document.getElementById('status');
        if (this.food && this.gameState === 'running') {
            const foodType = this.food.type === 'apple' ? '🍎' : '☠️';
            statusText.innerHTML += ` | 当前食物: ${foodType}`;
        }
    }
    
    setupControls() {
        document.addEventListener('keydown', (e) => {
            if (this.gameState !== 'running') return;
            
            switch(e.key) {
                case 'ArrowUp':
                    if (this.snake.direction !== 'down') {
                        this.snake.direction = 'up';
                    }
                    break;
                case 'ArrowDown':
                    if (this.snake.direction !== 'up') {
                        this.snake.direction = 'down';
                    }
                    break;
                case 'ArrowLeft':
                    if (this.snake.direction !== 'right') {
                        this.snake.direction = 'left';
                    }
                    break;
                case 'ArrowRight':
                    if (this.snake.direction !== 'left') {
                        this.snake.direction = 'right';
                    }
                    break;
            }
        });
        
        // Initialize game loop with base speed
        this.updateGameSpeed(this.baseSpeed);
    }
    
    updateGameSpeed(speed) {
        this.baseSpeed = speed;
        this.currentSpeed = this.baseSpeed * Math.pow(this.speedMultiplier, Math.floor(this.score / 10));
        
        // Reset interval with new speed
        if (this.gameLoop) {
            clearInterval(this.gameLoop);
        }
        
        this.gameLoop = setInterval(() => {
            if (this.gameState === 'running') {
                this.moveSnake();
            }
        }, this.currentSpeed);
        
        // Update UI
        document.getElementById('speedValue').textContent = Math.round(this.currentSpeed);
    }
    
    moveSnake() {
        if (this.gameState !== 'running') return;
        
        if (this.isAIEnabled) {
            this.snake.direction = this.decideNextMove();
        }
        
        // Calculate new head position
        const head = { x: this.snake.position.x, y: this.snake.position.y };
        
        switch(this.snake.direction) {
            case 'up': head.y--; break;
            case 'down': head.y++; break;
            case 'left': head.x--; break;
            case 'right': head.x++; break;
        }
        
        // Check collisions
        if (this.checkCollision(head)) {
            endGame();
            return;
        }

        // Consume energy for movement
        this.energy = Math.max(0, this.energy - this.moveEnergyCost);
        
        // Check if snake runs out of energy
        if (this.energy <= 0) {
            this.energy = 0;
            document.getElementById('status').textContent = '能量耗尽！游戏结束';
            endGame();
            return;
        }

        // Update snake position
        this.snake.position = head;
        this.snake.trail.push({ ...head });
        
        // Check for food collisions
        const eatenApple = this.foods.apples.findIndex(apple => 
            apple.x === head.x && apple.y === head.y);
        
        const eatenPoison = this.foods.poisons.findIndex(poison => 
            poison.x === head.x && poison.y === head.y);
        
        if (eatenApple !== -1) {
            // Positive effects
            const oldEnergy = this.energy;
            const oldScore = this.score;
            
            this.energy = Math.min(this.maxEnergy, this.energy + this.foodTypes.apple.energyGain);
            this.score += this.foodTypes.apple.scoreGain;
            this.snake.length += 1;
            
            // Show effect feedback
            document.getElementById('status').textContent = 
                `吃到苹果! 能量 +${this.energy - oldEnergy}, 分数 +${this.foodTypes.apple.scoreGain}`;
            
            this.foods.apples.splice(eatenApple, 1);
            this.placeFoods();
        } else if (eatenPoison !== -1) {
            // Negative effects
            const oldEnergy = this.energy;
            const oldScore = this.score;
            
            this.energy = Math.max(0, this.energy + this.foodTypes.poison.energyLoss);
            this.score = Math.max(0, this.score + this.foodTypes.poison.scoreLoss);
            
            // Show effect feedback
            document.getElementById('status').textContent = 
                `吃到毒物! 能量 ${this.foodTypes.poison.energyLoss}, 分数 ${this.foodTypes.poison.scoreLoss}`;
            
            this.foods.poisons.splice(eatenPoison, 1);
            this.placeFoods();
        } else if (this.snake.trail.length > this.snake.length) {
            this.snake.trail.shift();
        }

        // Update UI with animations for changes
        this.updateUI();
    }
    
    checkCollision(position) {
        // Wall collision
        if (position.x < 0 || position.x >= this.currentMaze.length ||
            position.y < 0 || position.y >= this.currentMaze.length) {
            return true;
        }
        
        // Maze collision
        if (this.currentMaze[position.x][position.y] === 1) {
            return true;
        }
        
        // Self collision
        return this.snake.trail.some(segment => 
            segment.x === position.x && segment.y === position.y
        );
    }

    // Add perception method
    getPerception() {
        const head = this.snake.position;
        const perception = {
            up: this.lookInDirection(head, 'up'),
            down: this.lookInDirection(head, 'down'),
            left: this.lookInDirection(head, 'left'),
            right: this.lookInDirection(head, 'right'),
            foodDirection: this.getFoodDirection(head)
        };
        return perception;
    }

    lookInDirection(position, direction) {
        let x = position.x;
        let y = position.y;
        let distances = {
            wall: this.perceptionRange,
            food: -1
        };

        // Look ahead in the specified direction
        for (let i = 1; i <= this.perceptionRange; i++) {
            switch(direction) {
                case 'up': y--; break;
                case 'down': y++; break;
                case 'left': x--; break;
                case 'right': x++; break;
            }

            // Check for walls/obstacles
            if (this.checkCollision({x, y})) {
                distances.wall = i;
                break;
            }

            // Check for food
            if (this.food && x === this.food.x && y === this.food.y) {
                distances.food = i;
            }
        }
        return distances;
    }

    getFoodDirection(head) {
        if (!this.food) return null;
        return {
            dx: this.food.x - head.x,
            dy: this.food.y - head.y
        };
    }

    decideNextMove() {
        const perception = this.getPerception();
        
        // Random exploration
        if (Math.random() < this.explorationRate) {
            const possibleMoves = ['up', 'down', 'left', 'right'].filter(dir => 
                perception[dir].wall > 1 && // Not immediate wall
                this.isValidDirection(dir)  // Not opposite of current direction
            );
            return possibleMoves[Math.floor(Math.random() * possibleMoves.length)];
        }

        // Intelligent decision making
        const foodDir = perception.foodDirection;
        const possibleMoves = [];

        // Evaluate each direction
        ['up', 'down', 'left', 'right'].forEach(dir => {
            if (perception[dir].wall > 1 && this.isValidDirection(dir)) {
                const score = this.evaluateMove(dir, perception[dir], foodDir);
                possibleMoves.push({direction: dir, score: score});
            }
        });

        // Choose best move
        possibleMoves.sort((a, b) => b.score - a.score);
        return possibleMoves[0]?.direction || this.snake.direction;
    }

    evaluateMove(direction, perception, foodDir) {
        let score = 0;
        
        // Prefer moves with more space
        score += perception.wall * 2;

        // Prefer moves towards food
        if (foodDir) {
            switch(direction) {
                case 'up':
                    score += foodDir.dy < 0 ? 5 : 0;
                    break;
                case 'down':
                    score += foodDir.dy > 0 ? 5 : 0;
                    break;
                case 'left':
                    score += foodDir.dx < 0 ? 5 : 0;
                    break;
                case 'right':
                    score += foodDir.dx > 0 ? 5 : 0;
                    break;
            }
        }

        return score;
    }

    isValidDirection(newDir) {
        const opposites = {
            'up': 'down',
            'down': 'up',
            'left': 'right',
            'right': 'left'
        };
        return opposites[newDir] !== this.snake.direction;
    }

    setupPanelToggle() {
        const toggleBtn = document.getElementById('togglePanel');
        const controls = document.getElementById('controls');
        let isPanelVisible = true;

        toggleBtn.addEventListener('click', () => {
            isPanelVisible = !isPanelVisible;
            controls.classList.toggle('hidden');
            toggleBtn.innerHTML = isPanelVisible ? 
                '<span class="toggle-icon">☰</span>' : 
                '<span class="toggle-icon">→</span>';
        });
    }

    resetGame() {
        // Reset game state
        this.gameState = 'ready';
        
        // Reset snake
        this.snake = {
            position: { x: 1, y: 1 },
            direction: 'right',
            length: 3,
            trail: []
        };
        
        // Reset scores and energy
        this.score = 0;
        this.energy = this.maxEnergy;  // Reset energy to max
        
        // Generate new maze with current size
        this.generateMaze(this.mazeSizes[this.mazeSize].size);
        
        // Update UI
        this.updateUI();
    }

    // Add test-specific methods
    setTestState(state) {
        if (!this.isTestMode) return;
        Object.assign(this, state);
    }
}

// Global game instance
const game = new GameClient();

// UI handlers
function setMazeSize(size) {
    game.mazeSize = size;
    game.generateMaze(game.mazeSizes[size].size);
    document.getElementById('status').textContent = '已生成新迷宫';
    
    // Update active button state
    document.querySelectorAll('.maze-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    document.querySelector(`.maze-btn[onclick="setMazeSize('${size}')"]`).classList.add('active');
}

function resetGame() {
    // Reset game state
    game.gameState = 'ready';
    
    // Reset snake
    game.snake = {
        position: { x: 1, y: 1 },
        direction: 'right',
        length: 3,
        trail: []
    };
    
    // Reset scores and energy
    game.score = 0;
    game.energy = game.maxEnergy;  // Reset energy to max
    
    // Reset speed to base
    game.currentSpeed = game.baseSpeed;
    game.updateGameSpeed(game.baseSpeed);
    
    // Reset AI state
    game.isAIEnabled = false;
    
    // Generate new maze with current size
    game.generateMaze(game.mazeSizes[game.mazeSize].size);
    
    // Clear and redraw
    game.ctx.clearRect(0, 0, game.canvas.width, game.canvas.height);
    
    // Update UI
    game.updateUI();
    document.getElementById('status').textContent = 'Environment reset - Ready to start';
    document.getElementById('speedValue').textContent = game.baseSpeed;
    document.getElementById('speedSlider').value = game.baseSpeed;
}

// Game control functions
function togglePause() {
    const pauseBtn = document.getElementById('pauseBtn');
    if (game.gameState === 'running') {
        game.gameState = 'paused';
        pauseBtn.textContent = '继续';
        pauseBtn.style.background = '#4CAF50';  // Green for continue
        game.updateUI();
        document.getElementById('status').textContent = '游戏已暂停';
    } else if (game.gameState === 'paused') {
        game.gameState = 'running';
        pauseBtn.textContent = '暂停';
        pauseBtn.style.background = '#FFC107';  // Back to yellow for pause
        game.updateUI();
        game.render();  // Resume rendering
    }
}

function startGame() {
    game.gameState = 'running';
    // Reset pause button state when starting new game
    const pauseBtn = document.getElementById('pauseBtn');
    pauseBtn.textContent = '暂停';
    pauseBtn.style.background = '#FFC107';
    game.updateUI();
    game.render();
}

function endGame() {
    game.gameState = 'ended';
    // Reset pause button state when game ends
    const pauseBtn = document.getElementById('pauseBtn');
    pauseBtn.textContent = '暂停';
    pauseBtn.style.background = '#FFC107';
    game.updateUI();
    document.getElementById('status').textContent = `Game Over! Score: ${game.score}`;
}

// Add AI toggle button
function toggleAI() {
    game.isAIEnabled = !game.isAIEnabled;
    // Update UI to show AI status
    document.getElementById('status').textContent = 
        game.isAIEnabled ? 'AI模式已开启' : 'AI模式已关闭';
    
    // Update button appearance
    const aiButton = document.querySelector('.control-btn.ai');
    if (game.isAIEnabled) {
        aiButton.style.background = '#4CAF50';  // Green when AI is on
        aiButton.textContent = 'AI已开启';
    } else {
        aiButton.style.background = '#2196F3';  // Blue when AI is off
        aiButton.textContent = 'AI未开启';
    }
}

// Add speed control function
function updateSpeed(value) {
    game.updateGameSpeed(parseInt(value));
}

// Move test initialization to a function
function runGameTests() {
    if (typeof GameTester !== 'undefined') {
        const tester = new GameTester();
        tester.runAllTests().then(() => {
            console.log('Testing completed');
        }).catch(error => {
            console.error('Test error:', error);
        });
    } else {
        console.warn('GameTester not loaded. Skipping tests.');
    }
}

// Add a test button to the UI
function addTestButton() {
    const controlsDiv = document.querySelector('.game-controls');
    const testButton = document.createElement('button');
    testButton.className = 'control-btn test';
    testButton.textContent = '运行测试';
    testButton.onclick = runGameTests;
    controlsDiv.appendChild(testButton);
}

// Initialize test button after DOM loads
document.addEventListener('DOMContentLoaded', () => {
    addTestButton();
}); 